<?php

namespace leruge;

class ACR {
    private array $config = [
        'host' => '', // Host
        'access_key' => '', // Access Key
        'access_secret' => '', // Secret Key
    ];

    public function __construct() {
        $this->config = array_merge($this->config, config('acrcloud'));
    }

    // 获取签名
    private function getSignature($httpMethod, $httpUri, $dataType, $signatureVersion, $timestamp) {
        $string_to_sign = $httpMethod . "\n" . $httpUri ."\n" . $this->config['access_key'] . "\n" . $dataType . "\n" . $signatureVersion . "\n" . $timestamp;
        $signature = hash_hmac("sha1", $string_to_sign, $this->config['access_secret'], true);
        return base64_encode($signature);
    }

    // 请求
    private function request($filePath, $dataType = 'audio'): array {
        $filesize = '';
        $cFile = '';
        if ($dataType == 'audio') {
            $filesize = filesize($filePath);
            $cFile = new \CURLFile($filePath, mime_content_type($filePath), basename($filePath));
        }
        if ($dataType == 'fingerprint') {
            $filesize = filesize($filePath);
            $cFile = \acrcloud_create_fingerprint_by_file($filePath, 0, 12, false);
        }


        $httpMethod = 'POST';
        $httpUri = '/v1/identify';
        $signatureVersion = 1;
        $timestamp = time();

        $reqUrl = 'http://' . $this->config['host'] . "/v1/identify";
        $signature = $this->getSignature($httpMethod, $httpUri, $dataType, $signatureVersion, $timestamp);

        $postFields = [
            'sample' => $cFile,
            'sample_bytes' => $filesize,
            'access_key' => $this->config['access_key'],
            'timestamp' => $timestamp,
            'data_type' => $dataType,
            'signature_version' => $signatureVersion,
            'signature' => $signature,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $reqUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $errno = curl_errno($ch);
        curl_close($ch);
        if ($errno) {
            throw new \Exception('请求错误，请稍后再试');
        }
        return json_decode($result, true);
    }

    /**
     * @title 音频文件识别
     * @throws \Exception
     */
    public function recognizeByAudio($filePath): array {
        return $this->request($filePath);
    }

    /**
     * @title 指纹文件识别
     * @throws \Exception
     */
    public function recognizeByFingerprint($filePath): array {
        return $this->request($filePath, 'fingerprint');
    }
}